/*Layout Helper
 *david 2009112
 */
if(typeof(workspaceManagement)=="undefined"){
    workspaceManagement={};
}
workspaceManagement["currentWorkspaceId"]=0;
workspaceManagement["currentCategoryId"]=0;
workspaceManagement["workspaceCategoryMap"]={};
workspaceManagement["categoryWorkspaceListMap"]={};
workspaceManagement["categoryList"]=workspaceManagement["categoryList"]["category"];
workspaceManagement["categoryMap"]={};
workspaceManagement["getAllCategroylist"]=function(callback){
	DBHelper.getAllCategroylist(function(data){
		workspaceManagement["translateWrokspaceList"]($.evalJSON(data)["category"]);
		if(callback){
			callback(workspaceManagement["categoryList"]);
		}
	})
}
workspaceManagement["addWorkspaceLabel"]=function(wsid,targetcategroyid,callback){
	DBHelper.workspaceAddLabel(wsid,targetcategroyid,function(data){
		workspaceManagement["makeCategoryExpire"]([targetcategroyid]);
		workspaceManagement["makeWorkspaceExpire"]([wsid]);
		if(callback){
			callback(data);
		}
	})
}
workspaceManagement["makeCategoryExpire"]=function(arr){
    for (var i = 0; i < arr.length; i++) {
        if (workspaceManagement.categoryWorkspaceListMap[arr[i]]) {
            workspaceManagement.categoryWorkspaceListMap[arr[i]].expire = true;
        }
    }
}
workspaceManagement["makeWorkspaceExpire"] = function(arr){
    for (var i = 0; i < arr.length; i++) {
        if (workspaceManagement.workspaceCategoryMap[arr[i]]) {
            workspaceManagement.workspaceCategoryMap[arr[i]].expire = 0;
        }
    }
}
workspaceManagement["translateWrokspaceList"] = function(arr){
	var temp =[];
    for (var i = 0; i < arr.length; i++) {
        if(arr[i].id){
			temp.push(arr[i].id);
			if(!workspaceManagement["categoryMap"][arr[i].id]){
				workspaceManagement["categoryMap"][arr[i].id]={};
			}
			$.extend(true,workspaceManagement["categoryMap"][arr[i].id],arr[i]);
			workspaceManagement["categoryMap"][arr[i].id].index=i;
		}
    }
	workspaceManagement.categoryList=temp;
}
workspaceManagement["newLabel"]=function(callback,cfg){
	if(cfg&&cfg.type){
		utilWorkspaceStyle(cfg.type);
	}
    var self = this;
	workspaceManagement["utilPrompt"](QS_Lang.workspace["wsm_newlabeltitle"],function(txt){
		DBHelper.newLabel(txt, function(data){
			var o = eval("(" + data.replace(/\r\n/g, "") + ")");
			if(o["errorCode"]){
				if(o["errorCode"]==1062){
					Util.message(String.format(QS_Lang.workspace["wsm_newlabelexist"],txt));
				}else{
					Util.message(QS_Lang.workspace["wsm_createlabelfailed"]);
				}
			}else{
                if (callback) {
                    callback(data);
                }
			}
        })
	});
}
workspaceManagement["utilPrompt"]=function(title,callback){
	Util.prompt(title, function(txt){
        if (callback) {
            callback(txt.trim());
        }
    }, {
        validateMethod: function(txt){
            if (txt.trim() == "") {
                Util.message(QS_Lang.workspace["wsinput"]);
                return false;
            }
			if (txt.length>30) {
				Util.message(QS_Lang.workspace["wsm_maxchar"]);
                return false;
            }
            if (!QS_Validator.test(txt.trim(), 'name')) {
                return false;
            }
            return true;
        }
    })
}
var layoutOperation = function(container, callback){
    this.container = container;
    this.el = null;
    this.logo = null;
    this.callback = $.extend(true, {}, callback);
    this.tabmenu = null;
    //this.mapKey = "default";  
    this.wsType = "morn";
    this.extraWidth = 0;
    this.needChangeTabmenuItem = false;
    this.displayStyle = "thumbnail";// grid or thumbnail;
    this.menuKey="";
    this.labelMaps = {};
    var qslang=QS_Lang.workspace;
    this.tabmenuData = [{
        txt: qslang["wsm_mcreate"],
        val: "create"
    }, {
        txt: qslang["wsm_mcreatenew"],
        val: "createnew"
    }, {
        txt: qslang["wsm_mopenws"],
        val: "open"
    }, {
        txt: qslang["wsm_mdeletews"],
        val: "delete"
    }, {
        txt: qslang["wsm_mrename"],
        val: "renameWorkspace"
    }, {
        txt: qslang["wsm_mrefresh"],
        val: "refreshScreenshot"
    }, {
        type: 'separator'
    }, {
        txt: qslang["wsm_mmove"],
        val: "move",
        className:"customMenu m-move",
        subMenu: [{txt: qslang["wsm_mnewfolder"],val: "moveNewLabel"},
        {type: 'separator'},{
            txt: "",
            val: "content",
            className:"customMenu-content",
            selectable:false
        },{type: 'separator',className:"lh-move-more"},{txt: "More",val: "movemore",className:"lh-move-more"}
        ]
    }, {
        txt: qslang["wsm_mlabel"],
        val: "label",
        className:"customMenu m-label",
        subMenu: [{txt: qslang["wsm_mnewlabel"],val: "labelNewLabel"},
        {type: 'separator'},{
            txt: "<div class='lh-label-menu'><div>",
            val: "content",
            className:"customMenu-content",
            selectable:false
        },{type: 'separator',className:"lh-label-more"},{txt: "More",val: "labelmore",className:"lh-label-more"},{type: 'separator'},{txt: "Apply",val: "apply",className:"lh-apply-labels",selectable:true}]
    }];
    this.tabmenuDataMap = {
        "thumbnail_morn": [this.tabmenuData[2], this.tabmenuData[1]],
        "grid_morn": [this.tabmenuData[2], this.tabmenuData[1]],
        "thumbnail_my": [this.tabmenuData[2], this.tabmenuData[1], this.tabmenuData[3], this.tabmenuData[4], this.tabmenuData[5], this.tabmenuData[6], this.tabmenuData[7], this.tabmenuData[6], this.tabmenuData[8]],
        "grid_my": [this.tabmenuData[2], this.tabmenuData[1], this.tabmenuData[3], this.tabmenuData[4], this.tabmenuData[6], this.tabmenuData[7], this.tabmenuData[6], this.tabmenuData[8]]
    };
	this.showLoadingEl={move:{},label:{}};
    this.menuWidth=0;
    this.HTML = '<div class="workspace-layout-operation"><a href="javascript:void(0)" class="lo-operation-remove" style="display:none"></a><a href="javascript:void(0)" class="lo-operation-op"></a></div><img class="lh-morningstar-logo" src="IM/img_morningstar_logo.png"><div class="lh-marsk"></div>';
    this.init();
};
layoutOperation.prototype = {
    init: function(){
        var self = this;
        $(this.HTML).appendTo(this.container);
        this.el = this.container.find(".workspace-layout-operation");
        this.logo = this.container.find(".lh-morningstar-logo");
        this.tabmenu = new Util.CascadeMenu($("#layouthelper .lh-bd-right"), {
//            display: false,
//            autoHide: false
			display: false,
			isTraceMouse: true,
            autoHide: true,
            fixedDirection: false
        }, this.tabmenuDataMap[this._getMapkey()], {
            onClick: function(item){
                var v = item.data.val,needCall = false;
                if(v=="apply"){
                    self.operationHide();
                    self._updateWorkspaceCategoryMap();
                }else if(v=="labelmore"||v=="movemore"){
					QS_FullMarsk.show();
                    self.operationHide();
                    self._openMoreDialog(v=="labelmore"?"label":"move");
                }else if(v=="delete"){
					if(workspaceManagement.currentCategoryId=="0"){
						self._deleteWorkspaceForever();
						return;
					}
					utilWorkspaceStyle("confirm");
                    Util.confirm(QS_Lang.text["wsdelconfirm"], function(b){
                        if (b) {
                            self._makeCategoryExpire([workspaceManagement.currentCategoryId]);
                            self._makeWorkspaceExpire([workspaceManagement.currentWorkspaceId]);
                            self._modifyWorkspaceCategoryMap(workspaceManagement.currentWorkspaceId,workspaceManagement.currentCategoryId+"_"+0);
                        }
                    });
                }else if(v=="moveNewLabel"){
                    self._newLabelAndMove(workspaceManagement.currentWorkspaceId);
                }else if(v=="labelNewLabel"){
                    self._newLabelAndLabel(workspaceManagement.currentWorkspaceId);
                }else if(v=="refreshScreenshot"){
                    if (typeof(self.callback.operationCallback) != "undefined") {
                        self.callback.operationCallback("refreshScreenshot",workspaceManagement.currentWorkspaceId);
                    }
                }else if (v == "renameWorkspace") {
                    utilWorkspaceStyle("prompt");
                    workspaceManager.renameWorkspace(workspaceManagement.currentWorkspaceId, function(wsprofile){
                        gWsList[wsprofile.id]=wsprofile;
                        if (typeof(self.callback.finishOperation) == "function") {
                            self.callback.finishOperation(true, workspaceManagement.currentCategoryId);
                        }
                    });
                }
                else if(typeof(self.callback.menuOnClick) != "undefined") {
                        self.callback.menuOnClick(item);
                }
            }
        });
        this.el.find(".lo-operation-op").bind("mouseover.layoutoperation", function(e){
            if(self._getMapkey()!=self.menuKey){
                self.menuKey = self._getMapkey();
                self._reBindMenuData();
            }
            var o = $(this);
            var cpos = o.position();//current
            var pos = o.parent().position();
            if(self.needChangeTabmenuItem){
                self.tabmenu.reBind(self.tabmenuDataMap[self._getMapkey()], false);
            }
			var tabmenuTop=self.el.position().top+23+self.tabmenu.menu.height();
			var ctnHeight =self.tabmenu.container.height();
            self.tabmenu.show(e);
			if(tabmenuTop>ctnHeight){
				self.tabmenu.setPosition(pos.left+self.el.width()-self.tabmenu.menu.width()-2,ctnHeight-self.tabmenu.menu.height());//23=op.hegiht
			}else{
				self.tabmenu.setPosition(pos.left+self.el.width()-self.tabmenu.menu.width()-2,pos.top+22);//23=op.hegiht
			}
        })
        
        this.el.bind("click.layoutoperation", function(e){
            e.stopPropagation();
            self.callback.menuOnClick("open");
        })
        this.logo.bind("click.layoutoperation", function(){
            self.callback.menuOnClick({data:{val:"open"}});
        })
        
        this.el.find(".lo-operation-remove").bind("click.layoutoperation", function(e){
            e.stopPropagation();
            self._deleteWorkspaceForever();
        })
        this.el.bind("click.layoutoperation", function(e){
            e.stopPropagation();
        })
        this.el.hide();
    },
	_deleteWorkspaceForever:function(){
		var self = this;
		self.operationHide();
		utilWorkspaceStyle("confirm");
            Util.confirm(QS_Lang.workspace["wsm_confirmremovews"], function(f){
                if (f) {
                    workspaceManager.remove(workspaceManagement.currentWorkspaceId, false,function(){
						if (typeof(self.callback.finishOperation) == "function") {
                        self.operationHide();
                        self._makeCategoryExpire([workspaceManagement.currentCategoryId]);
						var clist =workspaceManagement.workspaceCategoryMap[workspaceManagement.currentWorkspaceId];
						var toExpireCategorys = [];
						if(typeof(clist)!="undefined"&&clist.list){
							for(var i =0;i<clist.list.length;i++){
								toExpireCategorys.push(clist.list["id"]);
							}
							self._makeCategoryExpire(toExpireCategorys);
						}
                        self.callback.finishOperation(true, workspaceManagement.currentCategoryId);
                    }
					});
                }
            });
	},
    _newLabelAndMove:function(wsid){
        utilWorkspaceStyle("prompt");
        var self = this;
		workspaceManagement["utilPrompt"](QS_Lang.workspace["wsm_newlabeltitle"],function(txt){
			 DBHelper.newLabelAndMoveWorkspace(wsid,workspaceManagement.currentCategoryId,txt, function(data){
                if (typeof(self.callback.operationCallback) != "undefined") {
					self._makeWorkspaceExpire([wsid]);
					self._makeCategoryExpire([workspaceManagement.currentCategoryId]);
                    self.callback.operationCallback("moveNewLabel",data);
                }
            })
		})
    },
    _newLabelAndLabel:function(wsid){
        utilWorkspaceStyle("prompt");
        var self = this;
		workspaceManagement["utilPrompt"](QS_Lang.workspace["wsm_newlabeltitle"],function(txt){
			DBHelper.newLabelAndLabelWorkspace(wsid,txt, function(data){
                if (typeof(self.callback.operationCallback) != "undefined") {
					self._makeWorkspaceExpire([wsid]);
                    self.callback.operationCallback("labelNewLabel",data);
                }
            })
		})
    },
    _openMoreDialog:function(v){
        var self = this;
		QS_FullMarsk.show();
        workspaceManager.openOpenFileWin(this._transformCascadeMenuDataToFileWinData(v),function(el){
            var o = $(el),key = o.attr("cmd");
            if (o.hasClass("rtq-chkbox")) {
                self.labelMaps[key].lastest = !o.hasClass("rtq-chkbox-off");
            }else{
                self._moveWorkspaceCategory(workspaceManagement.currentWorkspaceId,workspaceManagement.currentCategoryId,key);
				QS_FullMarsk.hide();
            }
        }, null, null, function(){
            self._updateWorkspaceCategoryMap();
        }, "More...", v=="label");
    },
    _transformCascadeMenuDataToFileWinData:function(t){
        var pretemp ={};
        $.extend(true,pretemp,this.labelMaps);
        var list = this._reBindMoveData(workspaceManagement.workspaceCategoryMap[workspaceManagement.currentWorkspaceId].list,t,true);
        var temp =[];
        if(t=="move"){
            for(var i =0;i<list.length;i++){
                temp.push({cmd:list[i].val,text:list[i].txt});
            }
        }else{
            for(var i =0;i<list.length;i++){
                if (pretemp.hasOwnProperty(list[i].val)) {
                    temp.push({
                        cmd: list[i].val,
                        text: list[i].txt,
                        checked: pretemp[list[i].val].lastest
                    });
                }
                else {
                    temp.push({
                        cmd: list[i].val,
                        text: list[i].txt,
                        checked: list[i].checked
                    });
                }
            }
        }
        if (t == "label") {
            //recover pre value
            $.extend(true,this.labelMaps,pretemp);
            return {
                "Add to label": temp
            };
        }
        else 
            return {
                "Move to folder": temp
            };
    },
    _showMoreOption:function(v,f){
        if(v=="move"){
            f?this.tabmenu.menu.find(".lh-move-more").show():this.tabmenu.menu.find(".lh-move-more").hide();
        }else{
            f?this.tabmenu.menu.find(".lh-label-more").show():this.tabmenu.menu.find(".lh-label-more").hide();
        }
    },
    _updateWorkspaceCategoryMap:function(){
        var str ="";
        for(var i in this.labelMaps){
            if(this.labelMaps[i].origin!=this.labelMaps[i].lastest){
                str +=i+"_"+(this.labelMaps[i].lastest==true?1:0)+",";
                this._makeCategoryExpire([i]);
            }
        }
        if(str.length>0){
            str = str.substr(0,str.length-1);
            this._modifyWorkspaceCategoryMap(workspaceManagement.currentWorkspaceId,str);
            this._makeWorkspaceExpire([workspaceManagement.currentWorkspaceId]);
        }
		QS_FullMarsk.hide();
    },
    _modifyWorkspaceCategoryMap:function(wsid,map){//categoryid__action   1_0,2_1,3_0    0 delete 1 add
        var  self = this;
        DBHelper.updateWorkspaceLabels(wsid,map,function(data){
            if(typeof(self.callback.finishOperation)=="function"){
                self.operationHide();
                self.callback.finishOperation(true,workspaceManagement.currentCategoryId);
            }
        });
    },
    _reBindMenuData:function(){
        var self = this;
        var data = this.tabmenuDataMap[this.menuKey];
        this.tabmenu.reBind(data,false);
        this.menuWidth = this.tabmenu.menu.width();
        var chk = self.tabmenu.getItemByVal("content","label");
        if(chk!=null){
            chk.el.find("a").remove();
        }
        if(this.wsType!="morn"){
    		this.showLoadingEl={move:self.tabmenu.getItemByVal("content","move").el,label:self.tabmenu.getItemByVal("content","label").el.find(".lh-label-menu")};
        }
        this.tabmenu.menu.find(".customMenu").bind("mouseover.layoutoperation",function(e){
            var t = $(e.target);
            var o = t.parent();
            if(t.attr("sq")!="0"){
                return;
            }
            var d =workspaceManagement.workspaceCategoryMap[workspaceManagement.currentWorkspaceId];
            if(o.hasClass("m-move")){
                var item = self.tabmenu.getItemByVal("content","move");
               if(d&&d.expire==1){
                    self._bindCustomeMenuOnDataReady("move",item.el,d.list);
                }else if(d&&d.expire==-1){
					//self._renderLoading("move");
					return;
				}else{
                    self._bindCustomMenu("move",item.el);
                }
            }else if(o.hasClass("m-label")){
                var item = self.tabmenu.getItemByVal("content","label");
                if(d&&d.expire==1){
                    self._bindCustomeMenuOnDataReady("label",item.el.find(".lh-label-menu"),d.list);
                }else if(d&&d.expire==-1){
					self._renderLoading("label");
					return;
				}else{
                    self._bindCustomMenu("label",item.el.find(".lh-label-menu"));
                }
            }
        })
    },
    _renderLoading:function(v){
		this.showLoadingEl[v].html("<img src='//rtqimg.morningstar.com/theme/black/loading.gif' />");
    },
    _makeCategoryExpire:function(arr){
        for(var i = 0;i<arr.length;i++){
            if(workspaceManagement.categoryWorkspaceListMap[arr[i]]){
                workspaceManagement.categoryWorkspaceListMap[arr[i]].expire = true;
            }
        }
    },
    _makeWorkspaceExpire:function(arr){
        for(var i = 0;i<arr.length;i++){
            if(workspaceManagement.workspaceCategoryMap[arr[i]]){
                workspaceManagement.workspaceCategoryMap[arr[i]].expire = 0;
            }
        }
    },
    _bindCustomMenu:function(type,container){
        var self = this;
        self._renderLoading(type);
		workspaceManagement.workspaceCategoryMap[workspaceManagement.currentWorkspaceId]={list:{},expire:-1};
        this._getWorkspaceCategoryList(workspaceManagement.currentWorkspaceId,function(data){
            workspaceManagement.workspaceCategoryMap[workspaceManagement.currentWorkspaceId]={list:data,expire:1};
            self._bindCustomeMenuOnDataReady(type,container,data);
			if(type=="move"){
				self._bindCustomeMenuOnDataReady("label",self.showLoadingEl["label"],data);
			}
        });
        
    },
    _bindCustomeMenuOnDataReady:function(type,container,data){
        var self = this;
        if (type == "move") {
            container.html(this._setMoveHTML(this._reBindMoveData(data, type)));
            container.find("ul").unbind("click").bind("click", function(e){
                var key = $(e.target).closest("li").attr("key");
                self.tabmenu.hide();
                if (workspaceManagement.currentCategoryId == 0) {
                    //self._makeCategoryExpire([key]);
                    self._workspaceAddLabel(workspaceManagement.currentWorkspaceId, key);
                }
                else {
                    //self._makeCategoryExpire([workspaceManagement.currentCategoryId,key]);
                    self._moveWorkspaceCategory(workspaceManagement.currentWorkspaceId, workspaceManagement.currentCategoryId, key);
                }
                //self._makeWorkspaceExpire(workspaceManagement.currentWorkspaceId);
            }).show();
        } else if (type == "label") {
            var d = this._reBindMoveData(data, type);
            container.html("");
            var t3 = new Util.ButtonGroup(container, d, {
                onClick: function(v, b){
                    self.labelMaps[v]["lastest"] = b.isSelected;
                }
            }, {
                type: 'checkbox',
                vertical: true
            });
        }
    },
    _workspaceAddLabel:function(wsid,targetcategroyid){
        var self = this;
        this._makeWorkspaceExpire([wsid]);
        this._makeCategoryExpire([targetcategroyid]);
        DBHelper.workspaceAddLabel(wsid,targetcategroyid,function(data){
			if($.evalJSON(data)==1062){
                Util.message(QS_Lang.workspace["wsm_movewsfailed"]);
			}
            self.callback.finishOperation(data,workspaceManagement.currentCategoryId);
        })
    },
    _moveWorkspaceCategory:function(wsid,sourcecategroyid,targetcategroyid){
        var self = this;
        this._makeWorkspaceExpire([wsid]);
        this._makeCategoryExpire([sourcecategroyid,targetcategroyid]);
        DBHelper.moveWorkspace(wsid,sourcecategroyid,targetcategroyid,function(data){
			if($.evalJSON(data)==1062){
				Util.message(QS_Lang.workspace["wsm_movewsfailed"]);
				return;
			}
            self.callback.finishOperation(data,workspaceManagement.currentCategoryId);
        })
    },
    _getWorkspaceCategoryList:function(wsid,callback){
        DBHelper.getWorkspaceCategoryList(wsid,function(data){
            if(callback){
                callback($.evalJSON(data).category);
            }
        })
    },
    _reBindMoveData:function(clist,type,isAll){
        var maxItem = 10;
        var separator = {
            type: 'separator'
        };
        var data = [],temp = [];
        var labellist = {};
        for(var i =0;i<clist.length;i++){
            labellist[clist[i]["id"]]=0;
        }
        this._showMoreOption(type,false);
        var needCheckMax = (typeof(isAll)=="undefined"||isAll==false)?true:false;
        var categorylist = workspaceManagement.categoryList;
		var categorymap = workspaceManagement.categoryMap;
        //for (var i = 0; i < categorylist.length; i++) {
		
			for(var i=0;i<categorylist.length;i++){
            var contain = labellist.hasOwnProperty(categorylist[i]);
            if(type=="move"){
                if(!contain){
                    maxItem --;
                    temp.push({txt:categorymap[categorylist[i]].name,val:categorymap[categorylist[i]].id});
                }
                if (needCheckMax&&maxItem == 0) {//if the label is more than or equals to 10
                   break;
                }
            }else{
                maxItem --;
                this.labelMaps[categorymap[categorylist[i]].id]={origin:contain,lastest:contain};
                if (needCheckMax&&maxItem <= 0) {//if the label is more than or equals to 10
                }else{
					temp.push({txt:categorymap[categorylist[i]].name,val:categorymap[categorylist[i]].id,checked:contain});
				}
            }
        }
		if(needCheckMax&&maxItem<=0){
			this._showMoreOption(type,true);
		}
        return temp;
    },
    _setMoveHTML:function(data){
        var str ="<ul class='lh-move-menu'>";
        for(var i = 0;i<data.length;i++){
            str +="<li key='"+data[i].val+"'><a href='javascript:void(0);'>"+data[i].txt+"</a></li>";
        }
        str +="</ul>";
        return str;
    },
    _getCascadeMenuPosition:function(){
        
    },
    _getMapkey:function(){
        return this.displayStyle+"_"+this.wsType;       
    },
    getCategoryWorkspaceList:function(categoryid,callback){
        var self = this;
        DBHelper.getCategoryWorkspaceList(categoryid,function(data){
            if(callback){
                callback(data);
            }
        })
    },
    show: function(size){//{left:0,top:10}
        this.needChangeTabmenuItem = false;
        if (this.wsType == "morn") {  // show the close button.
            this.extraWidth = 20;
            this.el.find(".lo-operation-remove").hide();
        }else {
            this.el.find(".lo-operation-remove").show();
            this.extraWidth = 0;
        }
        if (this.wsType == "morn" && this.displayStyle == "thumbnail") {
            //this.logo.show();
            this.logo.css({
                left: size.left ,
                top: size.top+20
            });
        }else {
            this.logo.hide();
        }
        this.el.show();
        this.el.css(size); 
    },
    hide: function(){
        this.tabmenu.hide();
    },
    operationHide:function(){
        this.tabmenu.hide();
        this.el.hide();
    },
    changeBoxStyle: function(){
        this.hide();
        this.el.hide();
        this.logo.hide();
    },
    changeBoxTransparent: function(v){
        this.el.css({
            backgroundColor: v
        });
    }
};
var labelManagement={
    newLabel:function(){
        
    },
    deleteLabel:function(){
        
    },
    getLabelList:function(){
        
    },
    getWorkspacesByLabel:function(){
        
    },
    renameLabel:function(){
        
    }
};
var layoutHelper = function(){
    this.layoutOperation = null;
	this.nagativeExpire = true;
    var qslang=QS_Lang.workspace;
    this.html = '<div id="layouthelper"><div class="pn_tpl">' +
    '<div class="hd">' +
    '<div class="lh-hd-wrap"><a href="javascript:void(0);" class="lh-creaetws">'+qslang["wsm_createws"]+'</a><div class="lh-hd-right"><div class="lh-search-wrap"><input class="qs-ui-ipt" value="'+qslang["wsm_searchws"]+'" type="text"/><a class="qs-ui-btn go lh-searchbutton" href="javascript:void(0);">'+qslang["wsm_gows"]+'</a></div><div class="rtq-wstb-separator lh-separator"></div><a href="javascript:void(0);" class="lh-layoutstyle lh-layoutstyle-thumbnail"></a><a href="javascript:void(0);" class="lh-layoutstyle lh-layoutstyle-grid"></a></div></div>' +
    '</div>' +
    '<div class="bd">' +
    '<div class="bd-bg lh-bd-left">' +
    '<div class="con-shadow"></div>' +
    '<div class="content" style="overflow: hidden; height: 224px;">' +
    '<a href="javascript:void(0);" class="lh-ws-nagative e-mornw">'+qslang["wsm_defaultws"]+'</a><a href="javascript:void(0);" class="lh-ws-nagative e-myw">'+qslang["wsm_savedws"]+'</a><div style="height:230px;" class="lh-ws-nagative-morn-wrap"></div>' +
    '</div>' +
    '<div class="lh-nagative-label-operation"><a class="qs-ui-btn gradient lh-new-folder" href="javascript:void(0);">'+qslang["wsm_newfolder"]+'</a><a class="qs-ui-btn gradient lh-delete-folder lh-delete-folder-disable" href="javascript:void(0);">'+qslang["wsm_delfolder"]+'</a></div>' +
    '</div>' +
    '<div class="bd-bg lh-bd-right">' +
    '<div class="workspace-hover"></div><div class="con-shadow"></div>' +
    '<div class="content" style="overflow: hidden; height: 224px;"><div class="notfound" style="display:none;padding-top:20px;padding-left:20px;">'+qslang["wsm_nomatchyour"]+'</div><ul class="clearfix workspace-ul"></ul><div class="datagrid-wrap rtq-wl" style="margin-right:12px;"></div>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '<div class="ft"><div></div></div>' +
    '</div></div>';
    this.el = null;
    this.contextMenuCategoryId = 0;
    this.animProxy = null;
    this.dTplList = null;
    this.ddlTpl = null;
    this.desktop = null;
    this.templates = [];
    this.userTemplates = [];
    this.wsType = "morn";
    this.workspaceObj = null;
    this.scrollPanel = null;
    this.datagrid = null;
    this.capturing = false;
    this.styleThumbnailEl = null;
    this.notfoundEl = null;
    this.styleGridEl = null;
    this.data = [];
    this.sid = "";
    this.categroyList = {};
    this.scrollPanelSavedWorkspace = null;
    this.categroyContextMenu = null;
    this.searchInputBoxEl = null;
    this.applyoperate = {};
    this.layoutstyle = "thumbnail";
    this.isSearch =false;
	this.dragObj=null;
    this.subtype = {
        Folder: "move",
        Label: "label"
    };
    this.dataGridColumn = [{
        header: qslang["wsm_cname"],
        dataIndex: 'name',
        width: "40%"
    }, {
        header: qslang["wsm_cdate"],
        dataType: "date",
        dataIndex: 'time',
		dataFormat: 'M/d/yyyy, h:mm a',
        width: "25%"
    }, {
        header: qslang["wsm_cowner"],
        dataIndex: 'owner',
        width: "15%"
    }, {
        header: qslang["wsm_cpower"],
        dataIndex: 'permission',
        width: "20%"
    }];
    this.init();
};
layoutHelper.prototype = {
	_unbindDrag:function(){
		this.hoverDom.unbind(".Dragable");
		this.dragObj = null;
	},
	_bindDrag:function(){
		if (this.dragObj == null) {
			var self = this;
			this.dragObj=new Util.Dragable(self.hoverDom[0], {
				onDragStart: function(e, proxy){
					self.isDrag=true;
					var li = self.dTplList.find('li[sid=' + self.sid + ']')[0];
					proxy.removeClass("layhelper-proxy-griddiv");
					proxy.html('<img src="' + li.data.img + '" class="layhelper-proxy-drag" alt="' + li.data.name + '">');
					proxy.dataObj = li.data;
					proxy.selectObj = self;
				},
				onDragEnd:function(e,proxy){
					self.isDrag=false;
				}
			}, {
				autoProxy: true,
				delay: 100,
				group: 'layouthelper',
				customClass: 'layhelper-proxy-div'
			});
		}
	},
	_bindDrop:function(cid){
		var li=this.templateNavativeEl.find('a[ckey=' + cid + ']')[0];
		var self=this;
		new Util.Dropable(li, {
                onEnter: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        proxy.removeClass('rtq-dd-drop-yes');
                    }
                },
                onDrop: function(e, proxy){
					 self.isDrag=false;
                     if (proxy.selectObj && proxy.selectObj == self) {
                        if (proxy.dataObj) {
							if (workspaceManagement.currentCategoryId == 0) {
                                 self.layoutOperation._workspaceAddLabel(proxy.dataObj.id,cid);
                            } else {
                                 self.layoutOperation._moveWorkspaceCategory(proxy.dataObj.id,workspaceManagement.currentCategoryId,cid);
                            }
                        }
                    }
                }
            }, {
                group:'layouthelper'
            });
	},
    buildTplList: function(datalist){
        var self = this;
        if (this.scrollPanel) {
            this.scrollPanel.scrollbarY.scrollTo(0);
        }
        datalist = datalist || this.templates;
		this.dTplList.find("li").remove();
        for (var i = 0; i < datalist.length; i++) {
            var li=$('<li class="workspace-li-item" role="' + datalist[i].role + '" sid="' + datalist[i].id + '"><div class="pic"><img src="' + datalist[i].img + '"/></div><div class="info"><strong>' + datalist[i].name + '</strong><p>' + QS_Lang.workspace["tb_lastsave"] + datalist[i].time + '</p></div></li>');
			li[0].data=datalist[i];
			this.dTplList.append(li);
        }
        this.dTplList.find('li').bind("mouseenter", function(e){
			var o = $(this);
            var size = self.getOpElPosition(o);
			if(!self.isDrag)self.sid = o.attr("sid");
			self.hoverDom.attr("sid",self.sid);
			self.hoverDom.show().css({
                        left: size.left,
                        top:  size.top
            });
			self.layoutOperation.show(size);
            workspaceManagement.currentWorkspaceId = self.sid;
        }).bind("mouseleave", function(e){
            if ((e.relatedTarget&&$(e.relatedTarget).attr("class")&&$(e.relatedTarget).attr("class").indexOf("operation") != -1) || $(e.relatedTarget).attr("class") == "workspace-hover") {
                return;
            }
            self.applyoperate = {};
			self.hoverDom.hide();
            self.layoutOperation.changeBoxStyle();
        });
		self.hoverDom.bind("click", function(e){
            var o = $(this);
			self.sid = o.attr("sid");
            self._menuOnClick({
                data: {
                    val: "open"
                }
            });
        });
        //for Chrome 4.x img no onload event[SHIT]
        if ($.browser.safari == true && $.browser.webkit == true) {
            this.dTplList.find('li').each(function(i){
                var id = this.getAttribute('sid');
                var img = this.getElementsByTagName('img')[0];
                if (id <= -10000 || !id || img.src.indexOf('IM/ms_template.gif') > -1) {
                    img.style.display = 'block';
                }
            });
        }
        //reload screenshot
        this.dTplList.find('img').bind('error', function(e){
            var _this = this;
            clearTimeout(this.reloadTimer);
            this.reloadTimer = -1;
            if (!this.reloadCount) {
                this.reloadCount = 0;
            }
            if (this.reloadCount >= 10) {
                this.reloadCount = 0;
                return;
            }
            this.reloadTimer = setTimeout(function(){
                _this.src = _this.src.split('?t=')[0] + '?t=' + ((Math.random() * 10000) | 1);
                _this.reloadCount++;
            }, 10000);
        }).bind('load', function(e){
            this.style.display = 'block';
        });
        if (this.scrollPanel) {
            this.scrollPanel.reSize();
        }
//        if (this.scrollPanelSavedWorkspace) {
//            this.scrollPanelSavedWorkspace.reSize();
//        }
    },
    _operationCallback:function(type,data){
        if(type=="moveNewLabel"||type=="labelNewLabel"){
            this._newLabelCallback(data);
        }else if(type=="refreshScreenshot"){
            updateScreenshot(data);
        }else if(type==""){
            
        }else if(type==""){
            
        }else if(type==""){
            
        }else if(type==""){
            
        }
    },
    _menuOnClick: function(item){
        var self = this;
        var id = this.sid;
        if (typeof item.data!='undefined' && typeof item.data.val != 'undefined') {
            switch (item.data.val) {
                case "open":
                    var oid = WorkspaceTabs.currentTab.id.toString();
                    self.showFx(function(){
                        workspaceManager.handleToolbar('show');
                        workspaceManager.open(id);
                        WorkspaceTabs.removeTab(WorkspaceTabs.getTabById(oid), false);
                        gWsList[oid] = null;
                        delete gWsList[oid];
                        self.hide();
                    });
                    break;
                case "create":
                case "createnew":
                    self.createWorkspace(id);
                    break;
            }
        }
    },
    _deleteWorkspace: function(id){
        if (this.layoutstyle == "thumbnail") {
            this.styleThumbnailEl.find("li[sid='" + id + "']").unbind(".lh").remove();
        }
        else {
            this.datagrid.removeRow(id);
        }
        this.layoutOperation.changeBoxStyle();
        this.scrollPanel.reSize();
    },
    createWorkspace: function(id){
        var self = this;
        //update name
        gWsList[WorkspaceTabs.currentTab.id].profile.name = QS_Lang.workspace["wsm_dwsname"];
        WorkspaceTabs.currentTab.txt = QS_Lang.workspace["wsm_dwsname"];
        WorkspaceTabs.currentTab.menu.find('span').html(QS_Lang.workspace["wsm_dwsname"]);
        
        var widgetsProfile = [];
        if (id && id != 0) {
            if (wsWidgets[id]) {
                $.extend(true, widgetsProfile, wsWidgets[id]);
                for (var i = 0, l = widgetsProfile.length; i < l; i++) {
                    widgetsProfile[i].id = idService.newMinusId();
                }
                self.showFx(function(){
                    self.buildWorkspace(widgetsProfile);
                });
            }
            else {
                getWidgets(id, function(s){
                    var r = $.evalJSON(s);
                    var len = r.list.length;
                    if (r && len > 0) {
                        widgetsProfile = [];
                        for (var i = 0; i < len; i++) {
                            widgetsProfile.push({
                                id: idService.newMinusId(),
                                profile: $.evalJSON(r.list[i].profile)
                            });
                        }
                    }
                    self.showFx(function(){
                        self.buildWorkspace(widgetsProfile);
                    });
                });
            }
        }
        else {
            self.showFx(function(){
                self.buildWorkspace([]);
            });
        }
    },
    show: function(){
        var self = this;
        this.desktop = $('body'); //WorkspaceTabs.currentTab.panel;
        this._savedWorkspaceCategoryClick();
        this.setOutSize(0, this.desktop.height() - 35);
		if(this.nagativeExpire){
			this.nagativeExpire=false;
			workspaceManagement["getAllCategroylist"](function(){
				self._createNagative();
			});
		}
        this.el.show();
    },
    hide: function(){
        var self = this;
        this.el.hide();
        WorkspaceTabs.currentTab.toolbarBtn.show();
		utilWorkspaceStyleRemove();
    },
    getWorkspaceItem: function(workspaceID){
        return this.dTplList.children('li[sid=' + workspaceID + ']');
    },
    updateScreenshot: function(workspaceID, feeback){
        var self = this;
        feeback = feeback == false ? feeback : true;
        this.capturing = false; // can mutli-capture 
        if (this.capturing) {
            if (feeback) {
                Util.alert(QS_Lang.text["wscapturealert"]);
            }
            return;
        }
        if (workspaceID > 0) {
            this.capturing = true;
            var wsitem = this.getWorkspaceItem(workspaceID);
            var dImg = wsitem.find('img').eq(0).hide();
            DBHelper.captureWorkspace(workspaceID, function(o){
                o = $.evalJSON(o);
                if (o && o.screenShotURL) {
                    gWsList[workspaceID].profile.screenShotURL = o.screenShotURL;
                    gWsList[workspaceID].profile.screenShotDate = o.screenShotDate;
                    if (wsitem.length > 0) {
                        dImg.attr('src', gWsList[workspaceID].profile.screenShotURL.replace(/^https?:/,"") + '?t=' + ((Math.random() * 10000) | 1)).removeClass('loading');
                    }
                }
                else {
                    if (wsitem.length > 0) {
                        dImg.attr('src', 'IM/ms_template.gif');
                    }
                }
                self.capturing = false;
            });
        }
    },
    setWorkspace: function(workspaceObj){
        this.workspaceObj = workspaceObj;
    },
    buildWorkspace: function(widgetsProfile){
        wsWidgets[this.workspaceObj.id] = widgetsProfile;
        this.workspaceObj.showHelper = false;
        gWsList[this.workspaceObj.id].profile.showHelper = false;
        gWsList[this.workspaceObj.id].profile.screenShotURL = null;
        this.workspaceObj.loadModules();
        this.hide();
        workspaceManager.handleToolbar('show');
        WorkspaceTabs.currentTab.toolbarBtn.addClass('toolbar-btn-open');
		//UserTrace
	    Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Activity, Qs_UserTrace.Source.Workspace, Qs_UserTrace.Oper.New, this.workspaceObj.txt, this.workspaceObj.id, "This is new workspace.");
    },
    showFx: function(callback){
		setTimeout(function(){
                if (callback) {
                    callback();
                }
            }, 0);
//        var self = this;
//        this.animProxy.css({
//            width: 233,
//            height: 158,
//            position: 'absolute',
//            opacity: 0,
//            background: QS_Style.layouthelperBG,
//            top: 0,
//            left: 0,
//            zIndex: 99999
//        }).show();
//        
//        var h = this.desktop.height();
//        var w = $('body').width();
//        this.animProxy.animate({
//            width: w,
//            height: h,
//            opacity: 1,
//            top: 36,
//            left: 0
//        }, 500, 'linear', function(){
//            setTimeout(function(){
//                if (callback) {
//                    callback();
//                }
//                self.animProxy.hide();
//            }, 0);
//        });
    },
    setOutSize: function(w, h){
        this.el.css({
            height: h
        }).find('.bd .lh-bd-left').css({
            height: h - 110 //110
        });
        this.el.find('.bd .content').css({
            height: h - 128 //110
        })
        this.scrollPanel.reSize(null, h - 110);
        if (this.datagrid != null) {
            this.datagrid.resize(null, h - 110);
        }
        this.scrollPanelSavedWorkspace.reSize(null, h - 186);
    },
    _pushDefaultTemplates: function(){
        if (this.templates.length > 0) {
            this.data = this.templates;
            return;
        }
        for (var i in gWsList) {
            if (i <= -10000 && i != -100000) {
                this.templates.push({
                    name: gWsList[i].profile.name.replace(/&/g, "&#38;"),
                    time: '03/15/2010, 01:25 AM',
                    img: gWsList[i].profile.screenShotURL.replace(/^https?:/,"") || 'IM/ms_template.gif',
                    id: i,
                    permission: "Read Only",
                    owner: "Morningstar",
                    role: "default"
                })
            }
        }
        this.data = this.templates;
    },
    _pushUserTemplates: function(){
        var dlist = [];
        for (var i in gWsList) {
            if (i > 0 && i != WorkspaceTabs.currentTab.id && !gWsList[i].profile.showHelper && !gWsList[i].isDeleted) {
                dlist.push({
                    name: gWsList[i].profile.name.replace(/&/g, "&#38;"),
                    time: this._formatDate(gWsList[i].updateTime || (new Date()).getFullYear() + '-' + ((new Date()).getMonth() + 1) + '-' + (new Date()).getDate()),
                    img: gWsList[i].profile.screenShotURL ? gWsList[i].profile.screenShotURL.replace(/^https?:/,"") + '?t=' + ((Math.random() * 10000) | 1) : 'IM/ms_template.gif',
                    id: gWsList[i].id,
                    permission: "Read/Write",
                    owner: "me",
                    role: "my"
                });
            }
        }
        this.userTemplates = dlist;
        this.data = dlist;
    },
    init: function(){
        this.el = $(this.html).appendTo("body");//.css({height:this.desktop.height()});
        this.hoverDom = this.el.find('.workspace-hover');
        this.dTplList = this.el.find('.pn_tpl .bd ul');
        this._pushDefaultTemplates();
        this.buildTplList(this.templates);
        this.animProxy = $('<div id="layouthelper-fx">').appendTo('body');
        this.styleThumbnailEl = this.el.find(".lh-bd-right ul");
        this.templateNavativeEl = this.el.find(".lh-ws-nagative-morn-wrap");
        this.labelOperationEl = this.el.find(".lh-nagative-label-operation");
        this.styleGridEl = this.el.find(".lh-bd-right .datagrid-wrap");
        this.searchInputBoxEl = this.el.find(".qs-ui-ipt");
        this.notfoundEl = this.el.find(".notfound");
		//workspaceManagement.categoryMap=this._transListToMap(workspaceManagement.categoryList);
		workspaceManagement["translateWrokspaceList"](workspaceManagement["categoryList"]);
        this._createNagative();
        this._bindEvent();
        var self = this;
        this.layoutOperation = new layoutOperation(this.el.find(".lh-bd-right"), {
            menuOnClick: function(data){
                self._menuOnClick(data);
            },
            remove: function(){
                self._menuOnClick("delete");
            },
            finishOperation:function(data,cid){
                self.layoutOperation.operationHide();
                if($.evalJSON(data)==true){
                    self._activeLabel(cid);
                }
            },
            operationCallback:function(type,data){
                self._operationCallback(type,data);
            }
        });
        this.scrollPanel = new Util.ScrollPanel(this.el.find('.pn_tpl .bd .lh-bd-right .content'));
        this.scrollPanelSavedWorkspace = new Util.ScrollPanel(this.templateNavativeEl);
    },
	_transListToMap:function(list,key){
		var id = typeof(key)=="undefined"?"id":key;
		var map ={};
		for(var i = 0;i<list.length;i++){
			map[list[i][id]]=list[i];
		}
		return map;
	},
    _createNagative: function(){
        var atag = null, clist = workspaceManagement.categoryList,self = this,temp=null;
        this.templateNavativeEl.find("a").remove();
		for (var i =0;i<clist.length;i++) {
			temp = workspaceManagement.categoryMap[workspaceManagement["categoryList"][i]];
            atag = $('<a href="javascript:void(0);" class="lh-ws-nagative level2" ckey=' + temp["id"] + '>' + temp["name"] + '</a>');
			this.templateNavativeEl.append(atag);
			this._bindDrop(temp["id"]);
        }
        this.el.find(".lh-ws-nagative").unbind(".lhblur");
        this.el.find(".lh-ws-nagative").bind("focus.lhblur", function(){
            $(this).blur();
        })
		this.templateNavativeEl.find(".level2").unbind("contextmenu").bind("contextmenu", function(e){
            var tar = $(this);
            self.contextMenuCategoryId = tar.attr("ckey");
            self.categroyContextMenu = new Util.CascadeMenu(self.templateNavativeEl, {
                display: false,
                autoHide: true,
                isTraceMouse: true
            }, [{
                txt: "Rename",
                val: "rename"
            }], {
                onClick: function(item){
                    self._renameLabel(self.contextMenuCategoryId);
                }
            });
            self.categroyContextMenu.show(e);
        });
    },
	syncSavedWorkspaceNagative:function(){
		
	},
    _showList: function(){
		this.layoutOperation.operationHide();
        this._changeLayoutStyle(this.layoutstyle);
        if (this.layoutstyle == "thumbnail") {
            this.buildTplList(this.data);
        }else if(this.layoutstyle == "grid") {
           this._bindDataGridData(this.data);
        }
        if (this.isSearch&&this.data.length == 0) {
            this._shwoNotFound();
        }else {
            this.notfoundEl.hide();
        }
        this.isSearch = false;
    },
    _bindEvent: function(){
        var self = this;
        self.el.find(".e-mornw").addClass("lh-nagative-on");
        self.el.mousewheel(function(){
            self.layoutOperation.changeBoxStyle();
        });

        this.el.find(".lh-bd-left .content").bind("click.lh", function(e){
            var tar = $(e.target);
            if(!tar.hasClass("lh-ws-nagative")){
                return;
            }
            if (tar.hasClass("e-mornw")) {
                self.wsType = "morn";
                self._pushDefaultTemplates();
                self._activeDeleteFolderButton(false);
                self.layoutOperation.wsType=self.wsType;
				workspaceManagement.currentCategoryId = 0;
                self._nagativeClick(tar);
				self._unbindDrag();
            }else if (tar.hasClass("e-myw")) {
				self._savedWorkspaceCategoryClick();
            }else if (tar.hasClass("level2")) {
                var ckey = tar.attr("ckey");
                self.wsType = "my";
                self.layoutOperation.wsType=self.wsType;
                workspaceManagement.currentCategoryId = ckey;
                self._activeLabel(ckey);
				self._bindDrag();
            }
            self.layoutOperation.operationHide();
        })
        this.el.find(".lh-creaetws").bind("click.lh", function(){
            self.createWorkspace();
        })
        this.el.find(".lh-searchbutton").bind("click.lh", function(){
            self._searchWorkspace();
        }).bind("focus", function(){
            $(this).select();
        }).bind("blur", function(){
            self.searchInputBoxEl.val("");
        })
        this.el.find(".qs-ui-ipt").bind("keyup", function(e){
            if (e.keyCode == 13) {
                self._searchWorkspace();
            }
        }).bind("focus", function(e){
            self.el.find(".qs-ui-ipt").val("");
        });
        this.el.find(".lh-layoutstyle").bind("click.lh", function(e){
            self.searchInputBoxEl.val(QS_Lang.workspace["wsm_searchws"]);
            var tar = $(this);
            if (tar.hasClass("lh-layoutstyle-thumbnail")) {
                if (self.layoutstyle == "thumbnail") {
                    return;
                }
                self.layoutOperation.changeBoxTransparent("#2e2e2e");
                self.styleThumbnailEl.find("li").show();
                self.layoutstyle = "thumbnail";
                self.el.find(".lh-layoutstyle-thumbnail").removeClass("lh-layoutstyle-thumbnail-off");
                self.el.find(".lh-layoutstyle-grid").removeClass("lh-layoutstyle-grid-on");
            }
            else if (tar.hasClass("lh-layoutstyle-grid")) {
                if (self.layoutstyle == "grid") {
                    return;
                }
                self.layoutOperation.changeBoxTransparent("transparent");
                self.layoutstyle = "grid";
                self.el.find(".lh-layoutstyle-thumbnail").addClass("lh-layoutstyle-thumbnail-off");
                self.el.find(".lh-layoutstyle-grid").addClass("lh-layoutstyle-grid-on");
            }
            self.layoutOperation.displayStyle=self.layoutstyle;
            self._showList();
            self.layoutOperation.changeBoxStyle();
            self.setOutSize(0, self.desktop.height() - 35);
        })
        this.labelOperationEl.bind("click.lh", function(e){
			self.layoutOperation.operationHide();
            var o = $(e.target);
            if (o.hasClass("lh-new-folder")) {
				workspaceManagement["newLabel"](function(data){
					self._newLabelCallback(data);
				},{type:"prompt"})
            }else if (o.hasClass("lh-delete-folder")) {
                    if (!o.hasClass("lh-delete-folder-disable")) {
                        self._deleteLabel();
                    }
            }
        })
    },
	_savedWorkspaceCategoryClick:function(){
		this._bindDrag();
		this._pushUserTemplates();
        this.wsType = "my";
        this._activeDeleteFolderButton(false);
       	workspaceManagement.currentCategoryId = 0;
        this.layoutOperation.wsType=this.wsType;
        this._nagativeClick(this.el.find(".e-myw"));
	},
    _nagativeClick:function(tar){
        this._nagativeClickChangeStyle(tar);
        this._showList();
    },
    _nagativeClickChangeStyle:function(tar){
        this.searchInputBoxEl.val(QS_Lang.workspace["wsm_searchws"]);
        this.templateNavativeEl.find(".level2").removeClass("lh-contextmenu-over");
        this.el.find(".lh-ws-nagative").removeClass("lh-nagative-on");
        tar.addClass("lh-nagative-on");
    },
    _activeLabel:function(ckey,callback){
        var self = this;
		this.layoutOperation.operationHide();
        this._activeDeleteFolderButton(true);
		workspaceManagement.currentCategoryId=ckey;
        //this._reBindCategoryWorkspaces(GOLBAL_DATA.categroyMap[ckey]);
        var map = workspaceManagement.categoryWorkspaceListMap[ckey];//GOLBAL_DATA.categroyMap[ckey];
        var ael = self._getClickEl(ckey);
        if(ael=="undefined"||ael==null||ael.length==0){
            self._savedWorkspaceCategoryClick();
            return;
        }
        this._nagativeClickChangeStyle(ael);
        if(map&&!map.expire){
            this._reBindCategoryWorkspaces(map.list);
             this._showList();
        }else{
            this.layoutOperation.getCategoryWorkspaceList(ckey,function(data){
				if(ckey!=workspaceManagement.currentCategoryId){
					return;
				}
                var o = $.evalJSON(data).list;
                var arr =[];
                workspaceManagement.categoryWorkspaceListMap[ckey]={list:o,expire:false};
                for(var i = 0;i<o.length;i++){
                    arr.push({time:o[i].updateTime,id:o[i].id,profile:$.evalJSON(o[i].profile)});
                }
                self._reBindCategoryWorkspaces(arr);
                self._showList();
                if(callback){
                    callback();
                }
            })
        }
    },
    _reBindCategoryWorkspaces:function(arr){
        var dlist = [];
        if (typeof(arr) != "undefined") {
            for (var ii = 0; ii < arr.length; ii++) {
                var id = arr[ii].id;
                if(typeof(gWsList[id])=="undefined"){
                    continue;
                }
                dlist.push({
                    name: gWsList[id].profile.name,
                    time: this._formatDate(gWsList[id].updateTime || (new Date()).getFullYear() + '-' + ((new Date()).getMonth() + 1) + '-' + (new Date()).getDate()),
                    img: gWsList[id].profile.screenShotURL ? gWsList[id].profile.screenShotURL.replace(/^https?:/,"") + '?t=' + ((Math.random() * 10000) | 1) : 'IM/ms_template.gif',
                    id: gWsList[id].id,
                    permission: "Read/Write",
                    owner: "me",
                    role: "my"
                });
            }
        }
        this.userTemplates = dlist;
        this.data = dlist;
        this.wsType = "my";
        
    },
    _renameLabel: function(cid){
        utilWorkspaceStyle("prompt");
        var self = this;
		workspaceManagement["utilPrompt"]("Rename",function(txt){
            DBHelper.renameLabel(cid, txt, function(data){
                var o = $.evalJSON(data);
                if (o["errorCode"]) {
                    if (o["errorCode"] == 1062) {
                        Util.message(String.format(QS_Lang.workspace["wsm_newlabelexist"],txt));
                    }
                    else {
                        Util.message(QS_Lang.workspace["wsm_createlabelfailed"]);
                    }
                }else if (o.category) {
                    workspaceManagement.categoryMap[o.category[0].id] = o.category[0];
                    self._getClickEl(o.category[0].id).html(o.category[0].name);
                }
                else {
                    Util.message(QS_Lang.workspace["wsm_renamelabelerror"]);
                }
            })
		})
//        Util.prompt("Rename", function(txt){
//            DBHelper.renameLabel(cid,txt, function(data){
//                var o = $.evalJSON(data);
//                if (o.category) {
//					workspaceManagement.categoryMap[o.category[0].id]=o.category[0];
//                    self._getClickEl(o.category[0].id).html(o.category[0].name);
//                }else {
//                    Util.message("Rename label failed.");
//                }
//            })
//        },{
//			validateMethod: function(txt){
//				if(txt.trim()==""){
//					Util.message("Please enter a name.");
//					return false;
//				}
//				if (!QS_Validator.test(txt.trim(), 'name')) {
//					return false;
//				}
//				return true;
//			}
//		})
    },
    _newLabelCallback:function(data){
        var o = eval("(" + data.replace(/\r\n/g, "") + ")"), c = null;
        if (o.category && typeof(o.category[0]) != "undefined") {
            c = o.category[0];
//            //workspaceManagement.categoryList.splice(0, 0, c);
//			workspaceManagement.categoryMap[c.id]=c;
//			var tempMap={};
//			tempMap[c.id]=c;
//			workspaceManagement.categoryMap=$.extend(true,tempMap,workspaceManagement.categoryMap);
           workspaceManagement.currentCategoryId=c.id;
            this._modifyLable(workspaceManagement.currentCategoryId,c.id);
//            if (this.scrollPanelSavedWorkspace.scrollbarY&&map.index&&workspaceManagement.categoryList.length>0) {
//                this.scrollPanelSavedWorkspace.scrollbarY.scrollTo(map.index/workspaceManagement.categoryList.length);
//            }
        }else{
			Util.message(QS_Lang.workspace["wsm_createlabelfailed"]);
		}
    },
    _modifyLable:function(id,cid){
        var self = this;
        workspaceManagement["getAllCategroylist"](function(){
            self._createNagative();
            self._activeLabel(id, function(){
                self.layoutOperation.operationHide();
                if (self.scrollPanelSavedWorkspace) {
                    self.scrollPanelSavedWorkspace.reSize(null, self.el.find(".bd .lh-bd-left").height() - 76);
                }
                if (cid) {
                    var percent = 0;
                    if (cid != 0) {
                        var map = workspaceManagement.categoryMap[cid];
                        if (self.scrollPanelSavedWorkspace.scrollbarY && map.index && workspaceManagement.categoryList.length > 0) {
                            percent = (map.index +1)/ workspaceManagement.categoryList.length;
                        }
                    }
                    setTimeout(function(){
                        self.scrollPanelSavedWorkspace.scrollbarY.scrollPercentTo(percent);
                    }, 100)
                }
            });
        })
        
    },
    _getClickEl:function(id){
        return this.el.find(".lh-ws-nagative[ckey=" + id + "]");
    },
    _deleteLabel: function(){
        utilWorkspaceStyle("confirm");
        var self = this;
        Util.confirm(QS_Lang.workspace["wsm_confirmdeletefolder"], function(f){
            if (f) {
                DBHelper.deleteLabel(workspaceManagement.currentCategoryId, function(data){
                    var o = $.evalJSON(data);
                    var id = o.category.length>0?o.category[0].id:0;
					var cmap = workspaceManagement.categoryWorkspaceListMap[workspaceManagement.currentCategoryId];
					var toExpireWorkspaces = [];
					if(cmap&&cmap.list){
                        for (var i = 0; i < cmap.list.length; i++) {
                            toExpireWorkspaces.push(cmap.list["id"]);
                        }
                        workspaceManagement["makeWorkspaceExpire"](toExpireWorkspaces);
					}
                    self._modifyLable(id,0);
                })
            }
        });
    },
    _activeDeleteFolderButton: function(f){
        if (f) {
            this.el.find(".lh-delete-folder").removeClass("lh-delete-folder-disable");
        }else {
            this.el.find(".lh-delete-folder").addClass("lh-delete-folder-disable");
        }
    },
    _searchWorkspace: function(){
        if (this.searchInputBoxEl.val() == QS_Lang.workspace["wsm_searchws"]) {
            return;
        }
        this.isSearch = true;
        var self = this;
        self.styleThumbnailEl.find("li").hide();
        self.el.find(".datagrid-wrap").hide();
        var arr = [];
        var key = self.searchInputBoxEl.val().replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\$/g, "\\$").replace(/\)/g, "\\)").replace(/\(/g, "\\(").replace(/\^/g, "\\^").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\*/g, "\\*").replace(/\+/g, "\\+").replace(/\?/g, "\\?").replace(/\./g, "\\.");
        var rgx = new RegExp(key, "i");
        var tempArr = self.templates;
        if (self.wsType == "my") {
            tempArr = self.userTemplates;
        }
        for (var i = 0; i < tempArr.length; i++) {
            if (tempArr[i].name.match(rgx) != null) {
                arr.push(tempArr[i]);
                flag = true;
            }
        }
        if (arr.length == 0) {
            self.notfoundEl.show();
            this.data = [];
            self.searchInputBoxEl.val("");
            return;
        }
        else {
            self.searchInputBoxEl.val("")
        }
        self.data = arr;
        self._showList();
    },
    _bindDataGridData: function(tpls){
        if (tpls.length > 0) {
            this.notfoundEl.hide();
        }
        var self = this;
        if (this.datagrid == null) {
            this.datagrid = new Util.DataGrid(this.styleGridEl, {}, {
                column: this.dataGridColumn,
                htmlLayer: 'div',
                autoWidth: true,
                indexColKey: 'id',
                autoHeight: false,
				rowDragable: true,
				rowDragDropGroup: 'layouthelper'
            }, {
                onRowSelected: function(a, b){
                    a.stopPropagation();
                    self.sid = b.data.id;
                    self._menuOnClick({data:{val:"open"}});
                },
				onRowDragStart: function(e, proxy, row){
					if(row.data.id<0){proxy.hide();return;}
					proxy.removeClass('layhelper-proxy-div');
                    proxy.addClass('layhelper-proxy-griddiv');
					proxy.html(row.data.name);
					proxy.dataObj = row.data;
					proxy.selectObj = self;
            	},
                onRowMouseover: function(e, o,row){//e, cell, row
                    self.datagrid.el.find(".rtq-grid-row").removeClass('rtq-grid-row-over');
                    self.layoutOperation.hide();
                    //add a parentobj
					var rid =o.id;//;; o.attr("rowid");
                    var role = self.datagrid.rows[rid].data.role;
                    if (self.wsType == "my") {
                        role = "mygrid";
                    }
                    if(!self.isDrag) self.sid = rid;
                    var size = self.getOpElPosition(o.el);// 
                    self.layoutOperation.show(size);
					workspaceManagement.currentWorkspaceId = self.sid;
                    o.el.addClass("rtq-grid-row-over");
                },
                onRowMouseout: function(e, el){//e, cell, row
                    if ($(e.relatedTarget).attr("class") != "workspace-layout-operation" && $(e.relatedTarget).attr("class").indexOf("lo-operation") == -1) {
                       // el.el.removeClass("rtq-grid-row-over");
                        self.applyoperate = {};
                        self.layoutOperation.changeBoxStyle();
                   }
				   if($(e.relatedTarget).attr("class") == "workspace-layout-operation"||$(e.relatedTarget).attr("class").indexOf("lo-operation") != -1){
				   	    el.el.addClass("rtq-grid-row-over");
				   }
                }
            });
        }
        this.datagrid.reBindData(tpls);
    },
    getOpElPosition:function(o){
        var pos = o.position(), size={left:0,top:0};
        if(this.layoutstyle == "grid"){
            size.left = o.position().left + o.children().eq(0).width() - 207;
            size.top =  o.position().top  + 32;
        }else if(this.layoutstyle == "thumbnail"){
            size.left = pos.left+25;
            size.top = pos.top+23;//26=margin-left+padding-left,23=margin-top+padding-top
        }
        return size;
    },
    _shwoNotFound: function(){
        this.notfoundEl.show();
        this.data = [];
        this.styleGridEl.hide();
        this.styleThumbnailEl.hide();
    },
    _formatDate: function(date){
        return workspaceManager.toolbar.formatDateTime(date);
    },
    _changeLayoutStyle: function(s, tpls){
        if (s == "thumbnail") {
            this.layoutstyle = "thumbnail";
            this.styleGridEl.hide();
            this.styleThumbnailEl.show();
        }
        else 
            if (s == "grid") {
                this.styleThumbnailEl.hide();
                this.styleGridEl.show();
                this.layoutstyle = "grid";
            }
    },
    clear: function(){
        this.el.unbind(".lh");
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    }
};
var LayoutHelper = null;
function getMapLength(map){
	var j =0;
	for(var i in map){
		if(i){
			j++;
		}
	}
	return j;
}
function utilWorkspaceStyle(type){
    QS_FullMarsk.show();
    if (type == "prompt") {
        $(".rtq-prompt").addClass("util-workspace-style");
    }else if (type == "confirm") {
        $(".rtq-confirm").addClass("util-workspace-style");
    }
}
function utilWorkspaceStyleRemove(){
	$(".rtq-prompt").removeClass("util-workspace-style");
	$(".rtq-confirm").removeClass("util-workspace-style");
}
var workspaceSaveasWindow=function(){
    var qslang=QS_Lang.workspace;
	this.el = null;
	this.win = null;
	this.bodyEl = null;
	this.scrollPanel = null;
	this.categroyWrapEl=null;
	this.footerEl = null;
	this.wsCategroyId = 0;
	this.callback = null;
	this.html=	"<div class='qs-globe-ws-saveas'>"+
					"<div class='bd'>"+
						"<input type='text' class='qs-ui-ipt workspace-name' />"+
						"<a  class='saveoptions' href='javascript:void(0);'>"+qslang["sd_boption"]+"</a>"+
						"<div class='all-labels-list-wrap'><div class='all-labels-list'></div></div>"+
						"<a  class='qs-ui-btn rc newfloder' href='javascript:void(0);'>"+qslang["wsm_mnewfolder"]+"</a>"+
					"</div>"+
					"<div class='ft'>"+
						"<a href='javascript:void(0);' class='qs-ui-btn rc' val='cancel'><span>"+qslang["sd_bcancel"]+"</span></a>"+
						"<a href='javascript:void(0);' class='qs-ui-btn rc' val='ok'><span>"+qslang["sd_bok"]+"</span></a>"+
					"</div>"+
				"</div>";
	this._init();
};
workspaceSaveasWindow.prototype={
	show:function(name,callback){
		this.wsCategroyId = 0;
		this.callback=null;
		this.categroyWrapEl.find("a").removeClass("category-selected");
		if(name!=QS_Lang.workspace["wsm_dwsname"]){
			this.bodyEl.find(".workspace-name").val(name||"");
		}else{
			this.bodyEl.find(".workspace-name").val("");
		}
		if(callback){
			this.callback=callback;
		}
		this.el.show();
		if(this.categroyWrapEl.is(":visible")){//if categroyWrapEl is show, we will reload list.
			var self=this;
			workspaceManagement.getAllCategroylist(function(){
				self._loadAllCategory();
			});
		}
	},
	hide:function(){
		if(this.win){
			this.win.hide();
		}
	},
	_init:function(){
		var self = this;
		  this.win = new Util.RtqWindow(document.body, {
            windowReady: function(obj){
                obj.setHtml(self.html);
                self.el = obj.el;
                self.bodyEl = self.el.find(".bd");
                self.footerEl = self.el.find(".ft");
                self.categroyWrapEl = self.bodyEl.find(".all-labels-list");
                self.bodyEl.addClass("hide");
                self.scrollPanel = new Util.ScrollPanel(self.bodyEl.find(".all-labels-list"));
                self.hide();
				self._bindEvent();
            },
            beforeClosed: function(){
                
            }
        }, {
            title: QS_Lang.workspace["sd_title"],
            top: 100,
            width: 266,
            height: 135,
			minHeight:135,
            resizable: false,
            isGlobal: true,
            hasSettingPanel: false,
            closeAction: 'hide'
        });
        rtqWindowGroup.register(this.win);
        this.win.hide();
	},
	setWSName:function(name){
		if(name!=QS_Lang.workspace["wsm_dwsname"]){
			this.el.find(".workspace-name").val(name);
		}
	},
	_bindEvent:function(){
		var self= this;
		this.el.find(".saveoptions").bind("click.saveas",function(){
			var o =$(this);
			var flag = self.el.find(".all-labels-list-wrap:visible").length>0;
			if(flag){
				self.bodyEl.addClass("hide");
				self.win.setSize(266,135);
			}else{
				self.bodyEl.removeClass("hide");
				self.win.setSize(266,366);
				 workspaceManagement.getAllCategroylist(function(){
                        self._loadAllCategory();
                    });
			}
			
		}).bind("focus",function(){
			var o =$(this);
			o.blur();
		})
		this.categroyWrapEl.bind("click.saveas",function(e){
			if(e.target.tagName.toLowerCase()=='a'){
				var o = $(e.target);
				$(this).find("a").removeClass("category-selected");
				o.addClass("category-selected");
				self.wsCategroyId = o.attr("ckey");
			}
		})
		this.footerEl.bind("click",function(e){
			var o = $(e.target).attr("val");
			if(!o){
				o = $(e.target).parent().attr("val");
			}
			if(o=="ok"){
                var name = self.el.find(".workspace-name").val();
                if (name.length < 1) {
                    Util.message(QS_Lang.text["wsinput"]);
                    return false;
                }
                if ($.trim(name) == '') {
                    Util.message(QS_Lang.text["wsinput"]);
                    return false;
                }
                if (workspaceManager.hasWorkspaceName(name)) {
                    Util.message(QS_Lang.text["wsname"]);
                    return false;
                }
                if (name.length > 30) {
                    Util.message(QS_Lang.workspace["wsm_maxchar"]);
                    return false;
                }
				var keyWordResult=QS_Validator.testKeyWord(name,'workspacename');
				if(!keyWordResult.valid){
					Util.message(String.format(QS_Lang.workspace["wsm_renamewserror"],keyWordResult.promprStr));
                    return false;
				}
                if (!QS_Validator.test(name, 'name')) {
                    return false;
                }
				if(self.callback){
					self.callback(name,self.wsCategroyId);
				}
				self.hide();
			}else if(o=="cancel"){
				self.hide();
			}
		})
        this.bodyEl.find(".newfloder").bind("click.saveas", function(){
            workspaceManagement["newLabel"](function(data){
                var o = $.evalJSON(data);
                if (o && o["category"]) {
					var cid = o["category"][0].id;
                    // self.wsCategroyId = o["category"]["id"];
                    workspaceManagement.getAllCategroylist(function(){
                        self._loadAllCategory();
                        if (cid) {
                            var percent = 0;
                            if (cid != 0) {
                                var map = workspaceManagement.categoryMap[cid];
                                if (self.scrollPanel.scrollbarY && map.index && workspaceManagement.categoryList.length > 0) {
                                    percent = (map.index + 1) / workspaceManagement.categoryList.length;
                                }
                            }
                            setTimeout(function(){
								self.categroyWrapEl.find("a").removeClass("category-selected");
                            self.categroyWrapEl.find("a[ckey='"+cid+"']").addClass("category-selected");
                            self.wsCategroyId = cid;
                                self.scrollPanel.scrollbarY.scrollPercentTo(percent);
                            }, 100)
                        }
                        if (LayoutHelper) {
                            LayoutHelper.nagativeExpire = true;
                        }
                    });
                }
            });
        })
	},
	_loadAllCategory:function(){
		var str = "", clist = workspaceManagement["categoryList"],self = this,temp=null;
		for (var i =0;i<clist.length;i++) {
			temp = workspaceManagement.categoryMap[clist[i]];
            str += '<a href="javascript:void(0);" class="categorys" ckey=' + temp["id"] + '>' + temp["name"] + '</a>';
        }
		this.categroyWrapEl.find("a").unbind(".saveasfocus");
		this.categroyWrapEl.html(str);
		this.categroyWrapEl.find("a").bind("focus.saveasfocus",function(){
			$(this).blur();
		})
		if(this.scrollPanel){
			this.scrollPanel.reSize(null,190);
		}
	}
};
__updateScreenshoting=false;
function updateScreenshot(workspaceID, feeback){
        var self = this;
        feeback = feeback == false ? feeback : true;
        __updateScreenshoting = false; // can mutli-capture 
        if (__updateScreenshoting) {
            if (feeback) {
                Util.alert(QS_Lang.text["wscapturealert"]);
            }
            return;
        }
        if (workspaceID > 0) {
            __updateScreenshoting = true;
            var wsitem = [];
			var dImg ={};
			if(LayoutHelper!=null){
				wsitem = LayoutHelper.getWorkspaceItem(workspaceID);
				dImg = wsitem.find('img').eq(0).hide();
			}
            DBHelper.captureWorkspace(workspaceID, function(o){
                o = $.evalJSON(o);
                if (o && o.screenShotURL) {
                    gWsList[workspaceID].profile.screenShotURL = o.screenShotURL;
                    gWsList[workspaceID].profile.screenShotDate = o.screenShotDate;
                    if (wsitem.length > 0) {
                        dImg.attr('src', gWsList[workspaceID].profile.screenShotURL.replace(/^https?:/,"") + '?t=' + ((Math.random() * 10000) | 1)).removeClass('loading');
                    }
                }
                else {
                    if (wsitem.length > 0) {
                        dImg.attr('src', 'IM/ms_template.gif');
                    }
                }
                __updateScreenshoting = false;
            });
        }
};
var wsSaveasObj = null;
